/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.services.servlets;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.phonebooksharing.dto.LocationItem;
import com.phonebooksharing.dto.ReturnItem;

/**
 * Servlet implementation class LocationServlet
 */
public class LocationServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static Logger     log              = Logger.getLogger(LocationServlet.class);

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LocationServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter pw = response.getWriter();
        response.setContentType("text/html");
        pw.print("<html><head/><body><h1>Welcome to Phonebook Sharing Services!</h1><br/><h3>You should be posting here!</h3></body></html>");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
        try {

            if (!"u".equalsIgnoreCase(request.getParameter("ac"))) return;// skip if not this request

            ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
            LocationItem li = (LocationItem) ois.readObject();

            log.info("Received a location update, printing it...");
            log.info(li);

            oos.writeObject(new ReturnItem(true));

        } catch (Exception e) {
            e.printStackTrace();
            ReturnItem ri = new ReturnItem(false);
            ri.setErrorMsg(e.getLocalizedMessage());
            oos.writeObject(ri);
        }
    }
}
